package binarytree;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/24 11:18
 * https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
 * 二叉搜索树的最近公共祖先
 */
public class lowestCommonAncestor_II {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     *
     * 二叉搜索树，知道结点间的大小关系，从上到下遍历。
     * 只用搜索分支，若不知道结点间大小关系，需搜索整个树
     * @param root
     * @param p
     * @param q
     * @return
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (root.val > p.val && root.val > q.val) {
            TreeNode left = lowestCommonAncestor(root.left, p, q);
            if (left != null) {
                return left;
            }
        }
        if (root.val < p.val && root.val < q.val) {
            TreeNode right = lowestCommonAncestor(root.right, p, q);
            if (right != null) {
                return right;
            }
        }
        //此时 root一定大于一个数，小于一个数
        return root;
    }

    public static void main(String[] args) {

    }
}
